package com.ysd.lis.service.lab.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.LabChannelMapper;
import com.ysd.lis.mapper.lab.LabFeeitemVsItemDictMapper;
import com.ysd.lis.mapper.lab.LabInstrSetupMapper;
import com.ysd.lis.mapper.lab.LabItemDictMapper;
import com.ysd.lis.request.DeleteParam;
import com.ysd.lis.request.lab.LabFeeitemVsItemDictDto;
import com.ysd.lis.service.lab.LabFeeitemVsItemDictService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bai
 * @since 2023-12-20
 */
@Service
public class LabFeeitemVsItemDictServiceImpl extends ServiceImpl<LabFeeitemVsItemDictMapper, LabFeeitemVsItemDict> implements LabFeeitemVsItemDictService {

    @Autowired
    LabFeeitemVsItemDictMapper feeitemVsItemdictMapper;
    @Autowired
    LabItemDictMapper itemDictMapper;
    @Autowired
    private LabInstrSetupMapper labInstrSetupMapper;

    @Autowired
    private LabChannelMapper labChannelMapper;

    @Override
    public Result findItemDictListByFeeId(String feeCode,String rptGroup) {
        if (ToolsUtils.isEmpty(feeCode)) {
            return Result.fail("申请项目id入参异常");
        }
        MPJLambdaWrapper<LabItemDict> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(LabItemDict.class)
                .selectAs(LabFeeitemVsItemDict::getFeeCode, LabItemDict::getFeeCode)
                .selectAs(LabFeeitemVsItemDict::getIsOptional, LabItemDict::getIsOptional)
                .selectAs(LabFeeitemVsItemDict::getId, LabItemDict::getFeeVSItemDictId)
                .leftJoin(LabFeeitemVsItemDict.class, p->p.eq(LabFeeitemVsItemDict::getItemNo,LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getRptGroup,LabItemDict::getRptGroup).eq(LabItemDict::getDelFlag,0))
                .eq(LabFeeitemVsItemDict::getFeeCode, feeCode)
                .eq(LabFeeitemVsItemDict::getRptGroup,rptGroup)
                .eq(LabFeeitemVsItemDict::getDelFlag, 0)
                .orderByAsc(LabFeeitemVsItemDict::getSeq);
        List<LabItemDict> itemDicts = itemDictMapper.selectList(mpjLambdaWrapper);
        if (CollectionUtils.isEmpty(itemDicts)){
            return Result.succ(itemDicts);
        }
        List<Map<String, Object>> itemListMaps = itemDicts.stream()
                .map(itemDict -> {
                    Map<String, Object> itemMap = new LinkedHashMap<>();
                    itemMap.put("id", itemDict.getId());
                    itemMap.put("feeCode", itemDict.getFeeCode());
                    itemMap.put("isOptional", itemDict.getIsOptional());
                    itemMap.put("itemNo", itemDict.getItemNo());
                    itemMap.put("itemNa", itemDict.getItemNa());
                    itemMap.put("feeVSItemDictId", itemDict.getFeeVSItemDictId());
                    itemMap.put("rptGroup", itemDict.getRptGroup());
                    itemMap.put("seq", itemDict.getSeq());
                    return itemMap;
                }).collect(Collectors.toList());
        List<String> itemNos = itemDicts.stream().map(LabItemDict::getItemNo).collect(Collectors.toList());

        MPJLambdaWrapper<LabInstrSetup> instrWrapper = new MPJLambdaWrapper<>();
        instrWrapper.selectAll(LabInstrSetup.class);
        instrWrapper.eq(LabInstrSetup::getDelFlag, 0);
        if (StringUtils.isNotBlank(rptGroup)) {
            instrWrapper.eq(LabInstrSetup::getRptGroup, rptGroup);
        }
        List<LabInstrSetup> labInstrSetups = labInstrSetupMapper.selectList(instrWrapper);
        if (ToolsUtils.isNotEmpty(labInstrSetups)){
            List<String> instrCodes = labInstrSetups.stream().map(LabInstrSetup::getInstrCode).collect(Collectors.toList());
            LambdaQueryWrapper<LabChannel>channelWrapper=new LambdaQueryWrapper();
            channelWrapper.in(LabChannel::getInstrCode,instrCodes);
            channelWrapper.in(LabChannel::getItemNo,itemNos);
            channelWrapper.eq(LabChannel::getDelFlag,"0");
            channelWrapper.eq(LabChannel::getRptGroup,rptGroup);
            List<LabChannel> channels = labChannelMapper.selectList(channelWrapper);
            //往数据里面塞入仪器的字段,value是通道号
            for (LabInstrSetup labInstrSetup : labInstrSetups) {
                for (Map<String, Object> itemListMap : itemListMaps) {
                    itemListMap.put(labInstrSetup.getInstrCode(),"");
                    channels.stream().filter(channel -> channel.getItemNo().equals(itemListMap.get("itemNo"))&& channel.getInstrCode().equals(labInstrSetup.getInstrCode())&& "1".equals(channel.getIsOpen())).findFirst().ifPresent(channel -> {
                        itemListMap.put(labInstrSetup.getInstrCode(),channel.getChannelCode());
                            });
                }
            }


        }
        return Result.succ(itemListMaps);
    }

    @Override
    public List<LabItemDict> findItemDictListByFeeCoods(List<String> feeCode, String rptGroup,String orgId) {

        MPJLambdaWrapper<LabItemDict> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(LabItemDict.class)
                .selectAs(LabFeeitemVsItemDict::getFeeCode, LabItemDict::getFeeCode)
                .selectAs(LabFeeitemVsItemDict::getIsOptional, LabItemDict::getIsOptional)
                .selectAs(LabFeeitemVsItemDict::getId, LabItemDict::getFeeVSItemDictId)
                .leftJoin(LabFeeitemVsItemDict.class, p->p.eq(LabFeeitemVsItemDict::getItemNo,LabItemDict::getItemNo).eq(LabFeeitemVsItemDict::getRptGroup,LabItemDict::getRptGroup).eq(LabItemDict::getDelFlag,0))
                .in(LabFeeitemVsItemDict::getFeeCode, feeCode)
                .eq(LabFeeitemVsItemDict::getRptGroup,rptGroup)
                .eq(StringUtils.isNotBlank(orgId), LabFeeitemVsItemDict::getOrgId,orgId)
                .eq(LabFeeitemVsItemDict::getDelFlag, 0)
                .orderByAsc(LabFeeitemVsItemDict::getSeq);
        return itemDictMapper.selectList(mpjLambdaWrapper);
    }

    @Override
    public Result addFeeItemVsItemDict(LabFeeitemVsItemDict labFeeitemVsItemDict) {
        if (ToolsUtils.isEmpty(labFeeitemVsItemDict)) {
            Result.fail("入参不可为空，入参异常");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            labFeeitemVsItemDict.setOrgId(sysUser.getOrgId());
        }
        labFeeitemVsItemDict.setIsOptional("1");
        boolean save = this.save(labFeeitemVsItemDict);
        if (save) {
            return Result.succ(1, "", null);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result deleteFeeitemVsItemdict(DeleteParam deleteParam) {
        if (ToolsUtils.isEmpty(deleteParam)) {
            Result.fail("入参不可为空，入参异常");
        }
        int i = feeitemVsItemdictMapper.deleteById(deleteParam.getId());
        if (i > 0) {
            return Result.succ(1, "移除成功", null);
        } else {
            return Result.fail("移除失败！");
        }
    }

    @Override
    public Result findDictItemByFeeItemId(String feeCode,String rptGroup, String keyWords,Long pageSize,Long pageIndex) {
        if (ToolsUtils.isEmpty(feeCode)) {
            return Result.fail("入参异常！");
        }

        Page<LabItemDict> page = new Page<>();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);

        MPJLambdaWrapper<LabItemDict> itemDictwrapper = new MPJLambdaWrapper<>();
        itemDictwrapper.eq(LabItemDict::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(keyWords)) {
            itemDictwrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNa, keyWords).or().like(LabItemDict::getItemNo, keyWords));
        }
        itemDictwrapper.selectAll(LabItemDict.class);
        itemDictwrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabItemDict::getRptGroupName);
        itemDictwrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabItemDict::getRptGroup);

        StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_FEEITEM_VS_ITEMDICT t2 WHERE t.ITEM_NO = t2.ITEM_NO AND t2. FEE_CODE = '" + feeCode + "' and t2.RPT_GROUP = '"+rptGroup+"' ");

        itemDictwrapper.notExists(existsSql.toString());
        itemDictwrapper.eq(LabItemDict::getRptGroup,rptGroup);
        itemDictwrapper.orderByAsc(LabItemDict::getSeq);
        Page<LabItemDict> labItemDicts = itemDictMapper.selectPage(page,itemDictwrapper);
        return Result.succ(1, "查询成功", labItemDicts);
    }

    @Override
    public Result saveBatchFeeItemVsItemDict(LabFeeitemVsItemDictDto dto) {
        List<LabFeeitemVsItemDict> feeitemVsItemDictList = dto.getFeeitemVsItemDictList();
        List<LabFeeitemVsItemDict> collect = feeitemVsItemDictList.stream().filter(a -> ToolsUtils.isEmpty(a.getId())).collect(Collectors.toList());
        boolean b = this.saveBatch(collect);
        if(b){
            return Result.succ(1, "成功", null);
        }else {
            return Result.fail(400,"失败","");
        }
    }


}
